package bg.code.commons.plugin.ui;

import bg.code.commons.builder.dto.RenderDTO;
import bg.code.commons.builder.idea.ProjectPluginConfig;
import bg.code.commons.builder.project.ToolConfigurationData;
import bg.code.commons.builder.utils.Strings;
import com.intellij.ide.actions.OpenProjectFileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author 郑兴泉 956607644@qq.com
 * @data 2020/3/18
 * 描述：
 */
public class ConfigDialog2 extends JDialog {
    private ProjectPluginConfig pluginrInfo;
    private String entityPackage;
    private String entityName;
    private String serviceFileName;
    private String serviceImplFileName;
    private String servicePackage;
    private String serviceImplPackage;
    private String actionPackage;
    private String actionFileName;
    private String htmlPaths;
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField servicePackageText;
    private JTextField serviceImplPackageText;
    private JTextField actionPackageText;
    private JTextField htmlPathText;
    private JCheckBox actionCheckBox;
    private JCheckBox htmlPathCheckBox;
    private TextFieldWithBrowseButton basePathText;
    private JTextField funNameText;
    private JCheckBox implCheckBox;
    private JCheckBox serviceCheckBox;
    private JComboBox templateSelect;
    private JComboBox templateEngine;
    private ToolConfigurationData configuration;

    public ConfigDialog2(ToolConfigurationData configuration, ProjectPluginConfig pluginEditorInfo, String entityPackage, String entityName) {
        this.configuration = configuration;
        this.pluginrInfo = pluginEditorInfo;
        this.entityPackage = entityPackage;
        this.entityName = entityName;
        this.serviceFileName = entityName + "Service";
        this.serviceImplFileName = entityName + "ServiceImpl";
        this.actionFileName = entityName + "Action";
        this.servicePackage = entityPackage.replace("entity", "service");
        this.serviceImplPackage = entityPackage.replace("entity", "service") + ".impl";
        this.actionPackage = entityPackage.replace("entity", "action");
        this.htmlPaths = "/" + entityName + "/";
        int w = 500;
        int h = 400;
        int x = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2.0D - (double) (w / 2));
        int y = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2.0D - (double) (h / 2));
        this.setContentPane(this.contentPane);
        this.setTitle("代码生成");
        this.setModal(true);
        this.setBounds(x, y, w, h);
        this.getRootPane().setDefaultButton(this.buttonOK);
        this.servicePackageText.setText(this.servicePackage + "." + this.serviceFileName);
        this.serviceImplPackageText.setText(this.serviceImplPackage + "." + this.serviceImplFileName);
        this.actionPackageText.setText(this.actionPackage + "." + this.actionFileName);
        this.htmlPathText.setText(this.htmlPaths);
        this.templateEngine.addItem("beetl");
        this.templateEngine.addItem("apache velocity");
        this.buttonOK.addActionListener((e) -> {
            this.onOK();
        });
        this.buttonCancel.addActionListener((e) -> {
            this.onCancel();
        });
        this.setDefaultCloseOperation(0);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                ConfigDialog2.this.onCancel();
            }
        });
        this.contentPane.registerKeyboardAction((e) -> {
            this.onCancel();
        }, KeyStroke.getKeyStroke(27, 0), 1);
        this.basePathText.addActionListener((e) -> {
            OpenProjectFileChooserDescriptor descriptor = new OpenProjectFileChooserDescriptor(false, false);
            descriptor.setHideIgnored(true);
            descriptor.setShowFileSystemRoots(false);
            descriptor.setRoots(new VirtualFile[]{LocalFileSystem.getInstance().findFileByPath(pluginEditorInfo.getProject().getBasePath())});
            descriptor.setTitle("请选择html生成目录");
            FileChooser.chooseFiles(descriptor, pluginEditorInfo.getProject(), (VirtualFile) null, (virtualFiles) -> {
                VirtualFile virtualFile = (VirtualFile) virtualFiles.get(0);
                String selectPath = virtualFile.getCanonicalPath();
                selectPath = selectPath.replace("\\\\", "/").replace("\\", "/");
                this.basePathText.setText(selectPath);
            });
        });
        if (Strings.isBlank(configuration.getTemplatePath())) {
            Messages.showErrorDialog("请先设置模板目录", "错误提示");
        } else {
            Path path = Paths.get(configuration.getTemplatePath(), new String[0]);
            File[] list = path.toFile().listFiles();
            File[] var11 = list;
            int var12 = list.length;

            for (int var13 = 0; var13 < var12; ++var13) {
                File file = var11[var13];
                if (!file.isFile()) {
                    this.templateSelect.addItem(file.getName());
                }
            }
        }

    }

    private void onOK() {
        String temp;
        try {
            if (this.htmlPathCheckBox.isSelected() && this.basePathText.getText().trim().length() == 0) {
                Messages.showErrorDialog("请选择HTML目录", "错误提示");
            } else if (this.funNameText.getText().trim().length() == 0) {
                Messages.showErrorDialog("请输入功能名称", "错误提示");
            } else {
                String moduleBasePath = this.pluginrInfo.getPsiFile().getVirtualFile().getCanonicalPath();
                temp = this.entityPackage.replaceAll("\\.", "/");
                moduleBasePath = moduleBasePath.replace(temp, "");
                moduleBasePath = moduleBasePath.replace("/" + this.entityName + ".java", "");
                RenderDTO renderDTO = new RenderDTO();
                renderDTO.setServicePath(Paths.get(this.configuration.getTemplatePath(), new String[]{this.templateSelect.getSelectedItem().toString(), "Service.java"}));
                renderDTO.setServiceImplPath(Paths.get(this.configuration.getTemplatePath(), new String[]{this.templateSelect.getSelectedItem().toString(), "ServiceImpl.java"}));
                renderDTO.setActionPath(Paths.get(this.configuration.getTemplatePath(), new String[]{this.templateSelect.getSelectedItem().toString(), "Action.java"}));
                renderDTO.setIndexPath(Paths.get(this.configuration.getTemplatePath(), new String[]{this.templateSelect.getSelectedItem().toString(), "Index.html"}));
                renderDTO.setEditPath(Paths.get(this.configuration.getTemplatePath(), new String[]{this.templateSelect.getSelectedItem().toString(), "Edit.html"}));
                renderDTO.setHtmlPath(this.htmlPathCheckBox.isSelected());
                renderDTO.setAction(this.actionCheckBox.isSelected());
                renderDTO.setServiceImpl(this.implCheckBox.isSelected());
                renderDTO.setService(this.serviceCheckBox.isSelected());
                renderDTO.setServicePackageText(this.servicePackageText.getText());
                renderDTO.setServiceImplPackageText(this.serviceImplPackageText.getText());
                renderDTO.setActionPackageText(this.actionPackageText.getText());
                renderDTO.setBasePathText(this.basePathText.getText());
                renderDTO.setHtmlPaths(this.htmlPaths);
                renderDTO.setTemplateEngine(String.valueOf(this.templateEngine.getSelectedItem()));
//                PreviewData dialog = new PreviewData(this, this.pluginrInfo.getProject(), renderDTO, moduleBasePath, this.buildData(this.pluginrInfo.getJavaFields()));
//                dialog.pack();
//                dialog.setVisible(true);
            }

        } catch (Throwable var5) {
            temp = var5.getMessage();
            if (temp == null && var5.getCause() != null) {
                temp = var5.getCause().getMessage();
            }

            Messages.showErrorDialog(temp, "错误提示");
            throw var5;
        }
    }

//    private HashMap buildData(List<JavaFieldVO> javaFields) {
//        JavaBaseVO baseVO = new JavaBaseVO();
//        baseVO.setEntityName(this.entityName);
//        baseVO.setEntityPackage(this.entityPackage);
//        baseVO.setServiceFileName(this.serviceFileName);
//        baseVO.setServicePackage(this.servicePackage);
//        baseVO.setServiceImplFileName(this.serviceImplFileName);
//        baseVO.setServiceImplPackage(this.serviceImplPackage);
//        baseVO.setActionFileName(this.actionFileName);
//        baseVO.setActionPackage(this.actionPackage);
//        baseVO.setFunName(this.funNameText.getText());
//        baseVO.setUserName(this.configuration.getUserName());
//        baseVO.setUserMail(this.configuration.getUserMail());
//        Optional optional = javaFields.stream().filter(JavaFieldVO::isPrimaryKey).findFirst();
//        if (optional.isPresent()) {
//            JavaFieldVO field = (JavaFieldVO) optional.get();
//            baseVO.setPrimaryKey(field.getColumnName());
//            if ("uuid".equals(field.getColumnName().toLowerCase())) {
//                baseVO.setUuid(true);
//            }
//        }
//
//        baseVO.setRichText(javaFields.stream().filter((javaFieldVO) -> {
//            return javaFieldVO.getText() == 4;
//        }).findFirst().isPresent());
//        baseVO.setAttachment(javaFields.stream().filter(JavaFieldVO::isAttachment).findFirst() != null);
//        baseVO.setMultiDict(javaFields.stream().filter(JavaFieldVO::isMultiDict).findFirst() != null);
//        baseVO.setOneOneRelation(javaFields.stream().filter(JavaFieldVO::isOneOne).findFirst() != null);
//        String templatePath = this.basePathText.getText();
//        if (this.htmlPathCheckBox.isSelected()) {
//            int start = templatePath.indexOf("WEB-INF");
//            if (start > -1) {
//                baseVO.setTemplatePath(templatePath.substring(start) + this.htmlPaths);
//            } else {
//                baseVO.setTemplatePath(templatePath + this.htmlPaths);
//            }
//        }
//
//        HashMap bindData = new HashMap(2);
//        bindData.put("base", baseVO);
//        bindData.put("fields", this.pluginrInfo.getJavaFields());
//        return bindData;
//    }

    private void onCancel() {
        this.dispose();
    }
}
